package com.mjk.filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;

import com.mjk.common.util.NumberUtil;
import com.mjk.model.info.User;
import com.mjk.model.system.Element;
import com.mjk.model.system.Menu;
import com.mjk.model.system.OperationLog;
import com.mjk.service.info.UserService;
import com.mjk.service.system.ElementService;
import com.mjk.service.system.MenuService;
import com.mjk.service.system.OperationLogService;
import com.mjk.vo.PermissionInfo;

import tk.mybatis.mapper.entity.Example;

@Order(1)
@WebFilter(filterName = "operationFilter", urlPatterns = "/api/*")
public class OperationFilter implements Filter{
	public static Logger log = Logger.getLogger(OperationFilter.class);
	@Autowired
    private ElementService elementService;
	@Autowired
	private UserService userService;
	@Autowired
	private OperationLogService operationLogService;
	
	private String startWith = "/api/user/login,/api/user/intact/info,/api/user/intact/menus";

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
			throws IOException, ServletException {
		log.debug("operationFilter开始....");
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		final String requestUri = request.getRequestURI();//.substring("/api".length());
		final String id = String.valueOf(request.getHeader("Authorization"));
		final String method = request.getMethod();
		log.debug("operationFilter请求地址：" + requestUri + "operationFilter请求方法：" + method);
		if(!isStartWith(requestUri) && !"GET".equals(method) && request != null && id != null){
			 // 通过userid、uri 获取 log对象
			 Example example = new Example(Element.class);
			 Example.Criteria criteria = example.createCriteria();
			 criteria.andEqualTo("uri", requestUri);
			 PermissionInfo info = elementService.getPermissionByUriAndMethod(requestUri, method);
			 User user = userService.selectByPrimaryKey(NumberUtil.parseInteger(id));
			 request.setAttribute("userName", user.getName());
			 if(info != null && user != null){
				 operationLogService.insertSelective(permission2Log(info, user));
			 }
         }
		
        filterChain.doFilter(servletRequest,servletResponse);
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
		log.debug("operationFilter启动....");
	}

	private OperationLog permission2Log(PermissionInfo info, User user) {
		OperationLog operationLog = new OperationLog();
		operationLog.setMenu(info.getMenu());
		operationLog.setOpt(info.getName());
		operationLog.setUri(info.getUri());
		operationLog.setCrtUser(user.getId()+"");
		operationLog.setCrtName(user.getName());
		operationLog.setCrtTime(new Date());
        return operationLog;
    }
	
    /**
     * URI是否以什么打头
     * @param requestUri
     * @return
     */
    private boolean isStartWith(String requestUri) {
        boolean flag = false;
        for (String s : startWith.split(",")) {
            if (requestUri.startsWith(s)) {
                return true;
            }
        }
        return flag;
    }
}
